package demo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.keepme.ep.common.service.SysServiceI;
import demo.entity.AcquiDataEntity;

/**
 * @author Administrator
 *
 */
public class DataAcquisitionConvert {
//	private static Logger logger = Logger.getLogger(DataAcquisitionConvert.class);

	public DataAcquisitionConvert() {
	}
	
	/**
	 * 新增 根据不同交易所品种的数据采集结果 对解盘师发布价格进行换算
	 * 只有白银/原油，换算
	 * @return
	 */
	public static String execConvert(String tempContent,String msgRoomId,String roomName, SysServiceI sysService, String tradeName) {
		String content = tempContent;
		if(!content.contains("^")){
			return content;
		}
		String result = "";
//		String tagAll = DataAcquisitionConvert.getTagAll(content);
		
		// 检索内容 白银^13.5^处支撑，^15.6^附近​... -> 字符串数组 [0] ^13.5^ [1] ^15.6^ ...
		List<String> contentTagList = DataAcquisitionConvert.getContentTagAllRegex(content);
		if(contentTagList!=null){
			for(String tagAll : contentTagList){
//				System.out.println(str);
				// 1.获取content中解盘师发布的价格（^价格^  如^14.7^）
				String tagContent = DataAcquisitionConvert.getTagContent(content);
				if(tagContent!=null){
					// 2.查AcquiDataEntity.tag
					/**
select id from tp_analyze_trade where room_id in(select t1.id as category_id from tp_analyze_category t1,tp_analyze_room t2 where t1.id=t2.category_code and t2.id='402881ea4fc09bed014fc0b66a42000b') and parent_category_id='ff808081512b29d101512b3efbcc000c'
					 **/
					String analyzeTradeId = "";  // 需要msgroomid，tp_analyze_trade.parent_category_id
					String sql = "select id from tp_analyze_trade where room_id in(select t1.id as category_id from tp_analyze_category t1,tp_analyze_room t2 where t1.id=t2.category_code "
							+ "and t2.id='"+ msgRoomId +"') "
							+ "and parent_category_id=(select id from tp_analyze_trade where trade_name='"+ tradeName +"' )";
					List<String> ucList = sysService.findListbySql(sql);
					for (Object obj : ucList) {
						String u =  (String) obj;
						analyzeTradeId = u;
					}
					if(!"".equals(analyzeTradeId) && analyzeTradeId!=null){
						List<AcquiDataEntity> acqList = sysService.findHql("from AcquiDataEntity where tag = ? ", analyzeTradeId);
//				List<AcquiDataEntity> acqList = acquiDataService.findHql("from AcquiDataEntity where tag = ? and status = ? ", tag ,1);
						if (!acqList.isEmpty()) {
							for(AcquiDataEntity a : acqList){
								if(a.getParseResult1()!=null){
									// 3.换算
									result = DataAcquisitionConvert.convert(a.getParseResult1(), tagContent, roomName, sysService);
									if(result!=null){
										// 4.替换原有解盘老师发布的价格
										content = content.replace(tagAll, result);
									}
								}
								
							}
						}
						
					}
				}
			}
		}
		return content;
	}
	/**
	 * 换算解盘师发布的价格
	 * 例如：国内交易所白银价格=国内白银价格最高价/现货白银最高价×解盘师解盘信息中的价格
	 * @param s1
	 * @return
	 */
	public static String convert(String s1,String s3, String roomName, SysServiceI sysService) {
		String result = "";
		String tag = "";
		String s2 = "";
		int xiaoshu = 0;
		try {
			// 查现货白银，或者纽约原油
			if("白银".equals(roomName)){
				tag = "^B^";
			}
			if("原油".equals(roomName)){
				tag = "^Y^";
				xiaoshu = 2;
			}
			AcquiDataEntity entity = sysService.findUniqueByProperty(AcquiDataEntity.class, "tag",tag);
			s2 = entity.getParseResult1();
			Double num1 = Double.parseDouble(s1);
			Double num2 = Double.parseDouble(s2);
			Double laoshi = Double.parseDouble(s3);
			// 1950/38.99*40
			Double r = num1/num2*laoshi;
			System.out.println("result="+r+"("+num1+"/"+num2+"*"+laoshi+")");
			// 四舍五入取整（3035.7875536480688）
			// 原油价格保留两位小数 其他保留整数
			// 暂时都保留整数
			result = Mas.numberFormat(r,xiaoshu);
		} catch (Exception e) {
//			logger.error("换算解盘师发布的价格[" +s1+"/"+s2+"*"+s3+ "]出错:" + e.getMessage());
			return null;
		} finally {
		}
		return result;
	}
	
	
	/**
	 * 根据发布内容 取出标签 问题是现在取不到 ^12.3^ 这怎么取？
	 *
select parse_result1 from tp_acqui_data where tag in (
select id from tp_analyze_trade where room_id in(
select t1.id as category_id from tp_analyze_category t1,tp_analyze_room t2 
 where t1.id=t2.category_code and t2.id='402881ea4fc09bed014fc0b66a42000b'
) and parent_category_id='ff808081512b29d101512b3efbcc000c'
)
	 *
	 *
	 * @param s1
	 * @return
	 */
	public static String getTag(String s1) {
		String result = "";
		try {
			int n1 = s1.indexOf("^");
//			System.out.println("n1="+n1);
			String s2 = s1.substring(n1+1);
			int n2 = s2.indexOf("^");
//			System.out.println("n2="+(n2+n1));
			result = s1.substring(n1,n2+n1+2);
			// 转成大写
			result = result.toUpperCase();
		} catch (Exception e) {
//			logger.error("抓取解盘师发布内容[" + s1 + "]出错:" + e.getMessage());
			return null;
		} finally {
		}
		return result;
	}
	
	
	/**
	 * 测试,^14.67^完成。 -> ^14.67^
	 * @param content
	 * @return
	 */
	public static List<String> getContentTagAll(String content) {
//		String[] str = new String[] {}; 
		List<String> uList = new ArrayList<String>();
		try {
			String s = content;
			String ToFind = "^";
			int index = 0;
			int count = 0;
			while (index != -1) {
				index = s.indexOf(ToFind); 
				if(index!=-1)
				{
					s = s.substring(index + ToFind.length()); 
					count++; 
				} 
			}
			System.out.println("一共有" + count + "个" + ToFind);
			
		} catch (Exception e) {
//			logger.error("抓取解盘师发布内容[" + content + "]出错:" + e.getMessage());
			return null;
		} finally {
		}
		return uList;
	}
	
	/**
	 * 测试,^14.67^完成。 -> ^14.67^
	 * @param s1
	 * @return
	 */
	public static String getTagAll(String s1) {
		String result = "";
		try {
			int n1 = s1.indexOf("^");
			String s2 = s1.substring(n1+1);
			int n2 = s2.indexOf("^");

			result = s1.substring(n1,n1+n2+2);
		} catch (Exception e) {
//			logger.error("抓取解盘师发布内容[" + s1 + "]出错:" + e.getMessage());
			return null;
		} finally {
		}
		return result;
	}
	/**
	 * 测试,^14.67^完成。 - > 14.67
	 * 获取content中解盘师发布的价格
	 * @param s1
	 * @return
	 */
	public static String getTagContent(String s1) {
		// ^TTBY^价格^
		String result = "";
		try {
			int n1 = s1.indexOf("^");
			String s2 = s1.substring(n1+1);
			int n2 = s2.indexOf("^");

			result = s1.substring(n1+1,n1+n2+1);
		} catch (Exception e) {
//			logger.error("抓取解盘师发布内容价格[" + s1 + "]出错:" + e.getMessage());
			return null;
		} finally {
		}
		return result;
	}
	
	public static void findHql(String hql, Object... param) {
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				System.out.println(i +" = "+ param[i]);
			}
		}
	}
	
	
	public static List<String> getContentTagAllRegex(String input) {
//		String input = "白银^13.5^处支撑，^15.6^附近";
		List<String> uList = new ArrayList<String>();
		try {
//			String regex="\\^(\\d+[.]\\d+)\\^";
			String regex="\\^(\\d+[.]\\d+)\\^";
			Pattern pattern=Pattern.compile(regex);
			Matcher matcher=pattern.matcher(input);
		  while(matcher.find()){
//				  System.out.println(matcher.group(1));
		        String tmpStr = "^"+matcher.group(1)+"^";
		        uList.add(tmpStr);
		  }
		  regex="\\^(\\d+)\\^";
		  pattern=Pattern.compile(regex);
		  
		  matcher=pattern.matcher(input);
		  // 找 49.00
		  while(matcher.find()){
//		        System.out.println(matcher.group(1));
			  String tmpStr = "^"+matcher.group(1)+"^";
			  uList.add(tmpStr);
		  }
		  
		} catch (Exception e) {
//			logger.error("抓取解盘师发布内容[" + content + "]出错:" + e.getMessage());
			return null;
		} finally {
		}
		return uList;
	}
	
	public static void main(String[] args) {
//		DataAcquisitionScanner date = new DataAcquisitionScanner();
//		Double num1 = date.getBY("http://www.zsgjs.com/index/a/quoteApi/tdatas?tids=XHAG");
//		Double num2 = date.getBY("http://www.zsgjs.com/index/a/quoteApi/tdatas?tids=TTAG");
//		Double laoshi = 14.22;
//		System.out.println(""+num1/num2*laoshi);
		
//		String s1 = "测试,^BY14.67^完成。";
//		System.out.println(getTagAll(s1));
//		String s2 = "99.9";
//		s1 = s1.replace(getTagAll(s1), s2);
//		System.out.println(s1);
		
//		findHql("from AcquiDataEntity where tag = ? and status = ? ", "^BY",1);
//		1950/38.99*40
//		String s1 =  convert("1950","38.99","40");
//		System.out.println(s1);
		
//		String s1 = "----白银跌破^13.5^处支撑，^15.6^附近^17.22^&^19^";
//		String s1 = "#美好的一天从斯迈普解盘开始，精彩不断，只为您的关注！大家周一好！#";
//		System.out.println(getTagAll(s1));
//		System.out.println(getTagContent(s1));
//		System.out.println(getTag(s1));
		
//		List<String> list = getContentTagAll(s1);
//		System.out.println(list.size());
		
//		System.out.println(getContentTagAllRegex(s1));
		
//		List<String> contentTagList = DataAcquisitionConvert.getContentTagAllRegex(s1);
//		if(contentTagList!=null){
//			for(String str : contentTagList){
//				System.out.println(getTagAll(str));
//				System.out.println(DataAcquisitionConvert.getTagContent(str));
//			}
//		}
		
	}
	
}
